package com.leyou.auth.service;

import com.leyou.auth.config.JwtProperties;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.enums.LyExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.feignClient.UserClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;

@Service
public class AuthService {
    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserClient userClient;

    private static final String USER_ROLE = "role_user";

    public void login(String username, String password, HttpServletResponse response) {
        //查询用户
        try {
            UserDTO user = userClient.queryUserByNameAndPwd(username, password);
            UserInfo userInfo = new UserInfo(user.getId(), user.getUsername(), USER_ROLE);
            //生成token
            String token = JwtUtils.generateTokenExpireInMinutes(userInfo, jwtProperties.getPrivateKey(), jwtProperties.getUser().getExpire());
            //token写入cookie
            CookieUtils.newCookieBuilder()
                    .response(response)
                    .httpOnly(true)
                    .domain(jwtProperties.getUser().getCookieDomain())
                    .name(jwtProperties.getUser().getCookieName())
                    .value(token)
                    .build();
        } catch (Exception e) {
            throw new LyException(LyExceptionEnum.INVALID_USERNAME_PASSWORD,e);
        }
    }
}
